package test.com.sky.thread;

public class WaitDemo {


    private static Integer poolSize = 0;

    private static final Object lock = new Object();


    public static void main(String[] args) {


        new Thread(() -> {

            synchronized (lock) {

                for (int i = 0; ; i++) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    poolSize++;
                    System.out.println("INFO  producer  " + Thread.currentThread().getName() + "  poolSize  " + poolSize);

                    if (poolSize == 10) {
                        lock.notifyAll();  // 唤醒消费者
                        try {
                            lock.wait();   //自己等待

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }


                }
            }


        }).start();

        new Thread(() -> {

            synchronized (lock) {


                for (int i = 0; ; i++) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    poolSize--;
                    System.out.println("INFO  consumer  " + Thread.currentThread().getName() + "  poolSize  " + poolSize);

                    if (poolSize == 0) {

                        lock.notifyAll();  //唤醒生产者
                        try {
                            lock.wait();  //自己等待
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        }).start();


    }


}
